package cn.gz.zoomtech.common;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;


public class MessageUtil {
	private static final Logger log = Logger.getLogger(MessageUtil.class);

	private static int sequenceId;
	private static int sequenceNumber;
	private static final SimpleDateFormat formater = new SimpleDateFormat("MMddHHmmss");
	private static final SimpleDateFormat formater2 = new SimpleDateFormat("yyyyMMddHHmmss");

	private final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
		99999999, 999999999, Integer.MAX_VALUE };

	public static int stringSizeOfInt(int x) {
		for (int i=0; ; i++)
			if (x <= sizeTable[i])
				return i+1;
	}

	/**
	 * 
	* package_name: cn.gz.zoomtech.uisp.phonepos.message
	* file_name:    MessageUtil.java
	* description: 获取序列号（带同步锁）
	* 2013-7-15下午5:13:04
	* Author: chenhui
	 * @return
	 */
	public synchronized static int getSequenceId(){
		if(MessageUtil.sequenceId<2147483647){ // 长整型
			MessageUtil.sequenceId++;
		}else{
			MessageUtil.sequenceId = 1;
		}
		return MessageUtil.sequenceId;
	}



	/**
	 * 
	* package_name: cn.gz.zoomtech.common
	* file_name:    MessageUtil.java
	* description: 
	* 2013-8-15下午5:52:22
	* Author: chenhui
	 * @return
	 */
	public synchronized static String getSequenceNumber(){
		StringBuilder sb = new StringBuilder(20);
		sb.append(formater.format(new Date())) ;
		if(MessageUtil.sequenceNumber<9999){
			MessageUtil.sequenceNumber++;
		}else{
			MessageUtil.sequenceNumber=1;
		}
		sb.append(MessageParameter.SYSTEM_ID);
		int intSize = stringSizeOfInt(MessageUtil.sequenceNumber);

		if(intSize<4){
			int lessSize = 4 - intSize;
			for(int i=0;i<lessSize;i++){
				sb.append("0");
			}
		}
		sb.append(MessageUtil.sequenceNumber);
		return sb.toString();
	}



	/**
	 * 
	* package_name: cn.gz.zoomtech.common
	* file_name:    MessageUtil.java
	* description: 
	* 2013-8-15下午5:52:34
	* Author: chenhui
	 * @param timeStamp
	 * @return
	 */
	public static byte[] getCheckSource(String timeStamp){
		MessageDigest md = null;
		byte[] b = null;
		String s = MessageParameter.SYSTEM_ID 
		+ MessageParameter.PASSWORD + timeStamp;
		try {
			log.debug( MessageParameter.PASSWORD+"CheckSource:"+s);
			md = MessageDigest.getInstance("MD5");
			md.update(s.getBytes());
			b = md.digest();
			//System.out.println(str);
		} catch (NoSuchAlgorithmException e) {
			log.error("",e);
		}
		return b;
	}

	public static String getTimeStamp(){
		return formater.format(new Date());
	}


	public static String getTimeStr(){
		return formater2.format(new Date());
	}

	public static void main(String args[]){
		int k = 1000;
		for(int i=0;i<k;i++){
			System.out.println(MessageUtil.getSequenceId());
		} 
	}
}
